package ttcamera.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import ttcamera.common.TTCameraCommand;
import ttcamera.common.TTCameraConstant;
import ttcamera.common.TTCameraGetHostIPV4;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class Utils extends AsyncTask<Void, Void, Void> {

	private Context mContext;
	private String mCommand;

	/**
	 * Send command over broadcast
	 * 
	 * @param command
	 *            : command which to send.
	 * @throws IOException
	 */
	public Utils(Context context, String command) {
		mContext = context;
		mCommand = command;
	}

	/**
	 * Get current subnetmark
	 * 
	 * @return Example: 192.168.1
	 */
	public static String getCurrentSubnetMark(Context context) {
		TTCameraGetHostIPV4 t = new TTCameraGetHostIPV4(context);
		Log.d(TTCameraConstant.TAG, t.getSubnetMask());
		return t.getSubnetMask();
	}

	/**
	 * Check the command is valid or not
	 * 
	 * @param command
	 * @return True if valid, otherwise => false
	 */
	public static boolean checkValidCommand(String command) {
		if (command.startsWith(TTCameraCommand.COMMAND_PREFIX)) {
			return true;
		}
		return false;
	}

	@Override
	protected Void doInBackground(Void... params) {
		String messageStr = mCommand;
		int server_port = TTCameraConstant.CAMERA_PORT_COMMAND;
		DatagramSocket s;
		try {
			s = new DatagramSocket();
			// s.connect(new InetSocketAddress(server_port));
			InetAddress local;
			local = Inet4Address.getByName(getCurrentSubnetMark(mContext)
					+ ".255");
			int msg_length = messageStr.length();
			byte[] message = messageStr.getBytes();
			DatagramPacket p = new DatagramPacket(message, msg_length, local,
					server_port);
			s.send(p);
			s.close();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}
